﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime;
using Framework.Components;
using tproto.antlr4;

namespace tproto.Maker
{

    class TprotoVisitor : tprotoBaseVisitor<TprotoFile>
    {
        protected TprotoContext context;
        protected TprotoFile file;
        protected TprotoProto proto;
        protected TprotoAttribute attribute;

        public override TprotoFile VisitProgram([NotNull] tprotoParser.ProgramContext context)
        {
            this.context = new TprotoContext();
            file = new TprotoFile(this.context);
            VisitChildren(context);
            return file;
        }
        public override TprotoFile VisitProtocolDeclaration([NotNull] tprotoParser.ProtocolDeclarationContext context)
        {
            proto = new TprotoProto(file);
            file.Protos.Add(proto);
            proto.Name = context.IDENTIFIER().GetText();

            VisitChildren(context);
            return file;
        }

        public override TprotoFile VisitFieldDeclaration([NotNull] tprotoParser.FieldDeclarationContext context)
        {
            attribute = new TprotoAttribute(proto);
            proto.Attributes.Add(attribute);

            attribute.Name = context.IDENTIFIER().GetText();

            // note
            StringBuilder strBdr = new StringBuilder();
            foreach (var noteDeclaration in context.noteDeclaration())
            {
                strBdr.Append(noteDeclaration.GetText());
            }
            attribute.Tag = strBdr.ToString();

            // type
            var typeDeclaration = context.typeDeclaration();
            var typeStr = typeDeclaration.GetText();
            attribute.Type = TprotoAttributeType.CreateTprotoAttributeType(attribute, typeStr);
            return file;
        }

        public override TprotoFile VisitPackageDeclaration([NotNull] tprotoParser.PackageDeclarationContext context)
        {
            file.Package = context.qualifiedName().GetText();
            return file;
        }

        public override TprotoFile VisitImportDeclaration([NotNull] tprotoParser.ImportDeclarationContext context)
        {
            file.Imports.Add(context.qualifiedName().GetText());
            return file;
        }
    }
}
